﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using ReagentStore.BLL;
using ReagentStore.ERM;
using ReagentStore.UTL;

namespace ReagentStore
{
	public partial class ProductDialog : Form
	{
		private readonly PassParamsHandler<Product> _feedbackHandler;
		private readonly DialogParam<Product> _param;

		private FormValidator _formValidator;

		public ProductDialog(DialogParam<Product> param, PassParamsHandler<Product> handler)
		{
			InitializeComponent();

			_feedbackHandler = handler;
			_param = param;

			InitializeCombo();
			InitializeControlsByParam();
			InitializeValidator();
		}

		private void InitializeValidator()
		{
			_formValidator = new FormValidator(errorProvider);

			_formValidator.Add(new RequiredValidator(comboManufacturer, "请输入厂商名称"));
			_formValidator.Add(new RequiredValidator(textSpcification, "请输入规格"));
			_formValidator.Add(new RequiredValidator(textBatch, "请输入批次编号"));
			_formValidator.Add(new DateTimeRangeValidator(dateExpiration, "失效期限应迟于明日", DateTime.Today.AddDays(1),
			                                              DateTime.MaxValue));
			_formValidator.Add(new RequiredValidator(comboReagent, "请选择试剂类型"));
		}


		private void InitializeCombo()
		{
			IList<Reagent> reagents = new ReagentBLL().DALAccessor.GetEntities();
			comboReagent.DataSource = reagents;
			comboReagent.DisplayMember = "Name";
			comboReagent.ValueMember = "ReagentID";

			comboReagent.SelectedIndex = -1;

			string[] manufacturers = new ProductBLL().DALAccessor.GetEntities().Select(p => p.Manufacturer).ToArray();
			var list = new AutoCompleteStringCollection();
			list.AddRange(manufacturers);
			comboManufacturer.AutoCompleteSource = AutoCompleteSource.CustomSource;
			comboManufacturer.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
			comboManufacturer.AutoCompleteCustomSource = list;
			comboManufacturer.DataSource = list;
			comboManufacturer.SelectedIndex = -1;
		}


		private void InitializeControlsByParam()
		{
			Product product = _param.Parameter;

			switch (_param.ActionType)
			{
				case ActionTypes.Insert:
					Text = "添加产品";

					if (product.ReagentID > 0)
						comboReagent.SelectedValue = product.ReagentID;
					else
						comboReagent.SelectedIndex = -1;

					dateExpiration.MinDate = DateTime.Today.AddDays(1);
					dateExpiration.Value = DateTime.Today.AddDays(1);

					break;

				case ActionTypes.Update:
					Text = "更新产品";
					comboManufacturer.Text = product.Manufacturer;
					textSpcification.Text = product.Specification;
					textBatch.Text = product.Batch;
					dateExpiration.MinDate = product.ExpirationDate;
					dateExpiration.Value = product.ExpirationDate;
					comboReagent.SelectedValue = product.ReagentID;

					break;

				case ActionTypes.Delete:
					Text = "删除产品";
					comboManufacturer.Text = product.Manufacturer;
					textSpcification.Text = product.Specification;
					textBatch.Text = product.Batch;
					dateExpiration.Value = product.ExpirationDate;
					comboReagent.SelectedValue = product.ReagentID;

					groupBox.Enabled = false;
					break;
			}
		}

		private void Feedback()
		{
			switch (_param.ActionType)
			{
				case ActionTypes.Insert:
				case ActionTypes.Update:
					_param.Parameter.ReagentID = (int) comboReagent.SelectedValue;
					_param.Parameter.Manufacturer = comboManufacturer.Text;
					_param.Parameter.Specification = textSpcification.Text;
					_param.Parameter.Batch = textBatch.Text;
					_param.Parameter.ExpirationDate = dateExpiration.Value;
					break;
				case ActionTypes.Delete:
					break;
			}

			PassParamsHandler<Product> handler = _feedbackHandler;
			if (handler != null)
				handler(_param);
		}

		private void ProductDialog_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (DialogResult != DialogResult.OK)
				return;

			if (_param.ActionType == ActionTypes.Insert)
				if (!_formValidator.IsValid())
				{
					e.Cancel = true;
					return;
				}

			if (_param.ActionType == ActionTypes.Delete)
			{
				const string pattern = "删除该产品，将会导致该产品所属的所有出入库记录一并被删除。\r\n确认执行吗?";
				DialogResult confirm = MessageBox.Show(pattern, "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
				if (confirm == DialogResult.No)
					return;
			}

			Feedback();
		}

		private void comboReagent_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty(comboReagent.ValueMember))
				return;

			if (comboReagent.SelectedIndex < 0)
				return;

			Reagent reagent = new ReagentBLL().DALAccessor.GetEntityById((int) comboReagent.SelectedValue);
			const string pattern = "常备量：{1}{0}\r\n\r\n预警量：{2}{0}\r\n\r\n预警天数：{3}天";
			labelDescription.Text = string.Format(pattern,
			                                      reagent.Unit,
			                                      reagent.StandingCount,
			                                      reagent.AlertCount,
			                                      reagent.AlertPeriod);
		}
	}
}